package com.omega.framework.common.validate.template;

import com.omega.framework.common.exception.ServiceException;
import com.omega.framework.common.model.BaseResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 字段属性校验模板
 *
 * @author Lv.
 * @date 2023/8/29 16:50
 */
@Component
public class CheckFieldTemplate implements ApplicationContextAware, InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(CheckFieldTemplate.class);
    private ApplicationContext applicationContext;
    private List<DataTypeValidate> dataTypeValidates;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, DataTypeValidate> serviceBeanMap = this.applicationContext.getBeansOfType(DataTypeValidate.class);
        if (serviceBeanMap.size() > 0) {
            this.dataTypeValidates = new ArrayList<>(serviceBeanMap.values());
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 校验属性
     *
     * @param param 请求参数对象
     */
    public void checkField(Object param) {
        if (param == null) {
            log.error("checkField,param is null");
            throw new ServiceException(BaseResponseCode.UNKOWN_EXCEPTION);
        } else {
            try {
                Field[] fields = param.getClass().getDeclaredFields();
                for (Field field : fields) {
                    for (DataTypeValidate dataTypeValidate : this.dataTypeValidates) {
                        dataTypeValidate.validateInvoke(field, param);
                    }
                }

            } catch (IllegalAccessException illegalAccessException) {
                log.error("字段校验异常：" + illegalAccessException);
                throw new ServiceException(BaseResponseCode.INVALID_PARA);
            }
        }
    }

}
